import HttpService from '../../service/HttpService'
import ApiUrl from '../../service/ApiUrl'
import Vue from 'vue'
import Util from '../../service/Util'

// mutations-type config
const Types = {
	GET_DETAIL_REQUEST: 'GET_DETAIL_REQUEST',
	GET_PRODUCT_DETAIL: 'GET_PRODUCT_DETAIL',
	GET_PRODUCT_DETAIL_SUCCESS: 'GET_PRODUCT_DETAIL_SUCCESS',
	GET_PRODUCT_DETAIL_FAILED: 'GET_PRODUCT_DETAIL_FAILED'
}


// init state
const state = {
    productDetail: {}
}

const getters = {
    productDetail: state => state.productDetail,
}
let loading = Util.loading();
// action
const actions = {
	getProductDetail ({commit, state}, productId){
		commit(Types.GET_DETAIL_REQUEST)
		let opts = {
			apiObj : ApiUrl.getGoodsDetail,
			path : {
				id : productId
			}
		};
		HttpService.accessAPI(opts, result => { 
			commit( Types.GET_PRODUCT_DETAIL_SUCCESS, {result})
		}, reason => { commit(Types.GET_PRODUCT_DETAIL_FAILED, { reason }) });
	}
}

// init mutations 
const mutations = {
	[Types.GET_DETAIL_REQUEST] ( state ){
		state.productDetail = {};
		loading.start();
	},
	[Types.GET_PRODUCT_DETAIL_SUCCESS] ( state, { result } ){
		if( result.banner ){
	    	result.banner += '?imageView2/2/w/700';
	    }else{
	    	result.banner = '/static/placeholder.png';
	    }
	    if( result.instruction ){
	    	result.instruction = Util.encodeHtml( result.instruction );
	    }
	    state.productDetail = result;
	    loading.close();
		console.log( 'mutations success', state.productDetail );
	},
	[Types.GET_PRODUCT_DETAIL_FAILED] ( state, { result } ){
		state.productDetail = {};
		loading.close();
		console.log( 'mutations success', result );
	}
}

export default {
  state,
  getters,
  actions,
  mutations
}